package UpdateFarmAction;

use strict;

use Athena::WebAPI::Response;
use Athena::FarmView;

sub execute {
  my $stInvocant = shift(@_);
  my $rRequest = shift(@_);
  my $rConn = shift(@_);
  my $rResponse = undef;
  my %hParams = ( @_ );
  my $stParams = \%hParams;
  my $stActionName = 'UpdateFarmAction';
  $rRequest->action($stActionName);
  my $stAction = $rRequest->param($stActionName);
  my $stErrMsg = "";
  my $stLb = $rRequest->cookie('AthenaEngineUrl') 
    || $rRequest->cookie('AthenaEngineHost') 
      . ":" . $rRequest->cookie('AthenaEnginePort');

  my $rFarms = Athena::Engine::Farm->new($rConn);
  $rFarms->refresh();
  my $rPhyss = Athena::Engine::Phys->new($rConn);
  $rPhyss->refresh();

  # send updates
  if ($rRequest->param('need_update') eq '1') {
    # allow for future additions
    my @arUpdateCols = ('on');
    my $key;
    foreach $key (keys(%{$rFarms->{table}})) {
      my $stCol;
      foreach $stCol (@arUpdateCols) {
	my $stParamVal = $rRequest->param("idx.".$key.".".$stCol);
	# only update if different
	if ($stParamVal ne $rFarms->{table}->{$key}->{$stCol}) {
	  $rFarms->{table}->{$key}->{update} = 1;
	  if ($stParamVal) {
	    $rFarms->{table}->{$key}->{$stCol} = 1;
	  }
	  else {
	    $rFarms->{table}->{$key}->{$stCol} = 0;
	  }
	}
      }
    }
    $rFarms->update();
  }

  my $rHiddenFields = {
		       $rRequest->getActionParam() => $rRequest->action(),
		       $stActionName => '',
		       'need_update' => 0
		      };
  my $rView = FarmView->new('lb' => $stLb,
			    'err_msg' => $stErrMsg,
			    'hidden_fields' => $rHiddenFields,
			    'action_name' => $stActionName,
			    'body_style' => $stParams->{body_style},
			    'table_style' => $stParams->{table_style},
			    'farms' => $rFarms,
			    'physs' => $rPhyss
			   );

  $rResponse = Response->new($rView);
  
  return $rResponse;
}

1;
